
@setlocal

@REM parameters: <workspace-path> <project-name> <url>

@REM parameters

@IF {%~3} == {} GOTO do_parameter_error
@IF NOT {%~4} == {} GOTO do_parameter_error

@SET strWorkspacePath=%~1
@SET strProjectName=%~2
@SET strUrl=%~3

@SET strScriptRoot=%~dp0
@cd /D "%strScriptRoot%"
@cd ..\bin
@SET strFossilPath=%cd%

@IF NOT EXIST "%strWorkspacePath%\ws" (@mkdir "%strWorkspacePath%\ws")
@IF %ERRORLEVEL% neq 0 GOTO do_create_directory_error
@IF NOT EXIST "%strWorkspacePath%\log" (@mkdir "%strWorkspacePath%\log")
@IF %ERRORLEVEL% neq 0 GOTO do_create_directory_error

@REM update

@IF NOT EXIST "%strWorkspacePath%\ws\%strProjectName%" goto do_clone
@ECHO Check update ...
@cd /D "%strWorkspacePath%\ws\%strProjectName%\tree"
@"%strFossilPath%\fossil" pull < "%strScriptRoot%fossil-client-fetch-repo.txt"
@IF %ERRORLEVEL% neq 0 goto do_pull_error
@ping -n 2 127.0.0.1 > nul
@"%strFossilPath%\fossil" update > "%strWorkspacePath%\log\pull.txt"
@IF %ERRORLEVEL% neq 0 goto do_update_error
@ping -n 2 127.0.0.1 > nul
@FIND "Already up-to-date" "%strWorkspacePath%\log\pull.txt"
@IF %ERRORLEVEL% neq 0 goto do_changed
@ECHO Unchanged.
@exit /B 1

@REM clone

:do_clone
@ECHO Fetch code ...
@mkdir "%strWorkspacePath%\ws\%strProjectName%"
@IF %ERRORLEVEL% neq 0 GOTO do_create_directory_error
@mkdir "%strWorkspacePath%\ws\%strProjectName%\repo"
@mkdir "%strWorkspacePath%\ws\%strProjectName%\tree"
@cd /D "%strWorkspacePath%\ws\%strProjectName%\repo"
@"%strFossilPath%\fossil" clone --save-http-password "%strUrl%" "%strProjectName%.fossil" < "%strScriptRoot%fossil-client-fetch-repo.txt"
@IF %ERRORLEVEL% neq 0 goto do_clone_error
@ping -n 2 127.0.0.1 > nul
@"%strFossilPath%\fossil" setting autosync off -R "%strProjectName%.fossil"
@"%strFossilPath%\fossil" setting crnl-glob *, -R "%strProjectName%.fossil"
@"%strFossilPath%\fossil" setting encoding-glob *, -R "%strProjectName%.fossil"
@"%strFossilPath%\fossil" setting binary-glob *, -R "%strProjectName%.fossil"
@cd "%strWorkspacePath%\ws\%strProjectName%\tree"
@"%strFossilPath%\fossil" open "%strWorkspacePath%\ws\%strProjectName%\repo\%strProjectName%.fossil"
@IF %ERRORLEVEL% neq 0 goto do_open_error
@ECHO Succeeded.
@exit /B 0

:do_changed
@ECHO Changed.
@exit /B 0

:do_parameter_error
@ECHO Usage: fossil-client-fetch-repo.bat ^<workspace-path^> ^<project-name^> ^<url^>
@exit /B 2

:do_create_directory_error
@ECHO Error: cannot create directory!
@exit /B 3

:do_pull_error
@ECHO Error: pull error.
@exit /B 4

:do_update_error
@ECHO Error: update error.
@exit /B 5

:do_clone_error
@ECHO Error: clone error.
@exit /B 6

:do_open_error
@ECHO Error: open error.
@exit /B 7
